package com.chen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.dto.CourseDTO;
import com.chen.dto.GradeDTO;
import com.chen.entity.Course;
import com.chen.entity.Grade;
import com.chen.mapper.ClassesMapper;
import com.chen.mapper.ExamPaperMapper;
import com.chen.mapper.GradeMapper;
import com.chen.mapper.SubjectMapper;
import com.chen.service.GradeService;
import com.chen.vo.GradeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 年级管理相关服务实现
 */
@Service
public class GradeServiceImpl extends ServiceImpl<GradeMapper, Grade> implements GradeService {

    // 班级
    @Autowired
    private ClassesMapper classesMapper;

    // 题目
    @Autowired
    private SubjectMapper subjectMapper;

    // 试卷
    @Autowired
    private ExamPaperMapper examPaperMapper;


    /**
     * 获取年级信息列表
     * @return
     */
    @Override
    public List<GradeVO> findAllGrade() {
        return baseMapper.findAllGrade();
    }

    /**
     * 根据年级id获取年级信息
     * @param id
     * @return
     */
    @Override
    public GradeVO findGradeById(Integer id) {
        Assert.isTrue(ObjectUtil.isNotEmpty(id), "年级id不能为空");
        Grade grade = baseMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(grade)) {
            return BeanUtil.toBean(grade, GradeVO.class);
        }
        return null;
    }

    /**
     * 修改年级信息
     * @param dto
     * @return
     */
    @Override
    public Integer updateGrade(GradeDTO dto) {
        Integer id = dto.getId();
        Assert.isTrue(ObjectUtil.isNotEmpty(id), "年级id不能为空");
        String name = dto.getName();
        Assert.isTrue(ObjectUtil.isNotEmpty(name), "年级名称不能为空");
        // 将要修改的年级信息
        Grade grade = Grade.builder().id(id).name(name).build();
        return baseMapper.updateById(grade);
    }

    /**
     * 新增年级信息
     * @param dto
     * @return
     */
    @Override
    public Integer saveGrade(GradeDTO dto) {
        String name = dto.getName();
        Assert.isTrue(ObjectUtil.isNotEmpty(name), "年级名称不能为空");
        // 将要修改的年级信息
        Grade grade = Grade.builder().name(name).build();
        return baseMapper.insert(grade);
    }

    /**
     * 删除年级信息
     * @param id
     * @return
     */
    @Override
    public Integer delGrade(Integer id) {
        Assert.isTrue(ObjectUtil.isNotEmpty(id), "年级id不能为空");
        // 班级数量
        Long classesCount = classesMapper.findCountByGradeId(id);
        // 试题数量
        Long subjectCount = subjectMapper.findCountByGradeId(id);
        // 试卷个数
        Long countByGradeId = examPaperMapper.findCountByGradeId(id);
        // 班级数量和试题数量都为0才能删除班级
        if (classesCount == 0 && subjectCount == 0 && countByGradeId == 0) {
            baseMapper.deleteById(id);
        }
        return 0;
    }


}
